package com.cloud.bssp.monitor.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cloud.bssp.monitor.entity.DruidMonitorDO;
import com.cloud.bssp.monitor.feign.SwaggerClient;
import com.cloud.bssp.monitor.service.DruidMonitorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description: druid监控
 * Create Date: 2021-03-30T14:06:36.337
 * Modified By：<br>
 * Modified Date：<br>
 * Why & What is modified：<br>
 *
 * @author weirx
 * @version 1.0
 */
@Slf4j
@Service
public class DruidMonitorServiceImpl implements DruidMonitorService {

    @Autowired
    private SwaggerClient swaggerClient;

    @Value("${spring.cloud.nacos.discovery.server-addr}")
    private String nacosService;

    @Value("${spring.cloud.nacos.discovery.namespace}")
    private String namespace;

    @Value("${druid.manage.name}")
    private String druidManagerUrl;

    @Value("${spring.application.name}")
    private String serviceName;

    private final static String getInstanceList = "/nacos/v1/ns/instance/list";

    @Override
    public Page<DruidMonitorDO> page(Page<DruidMonitorDO> page) {
        List<DruidMonitorDO> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>(2);
        map.put("namespaceId", namespace);
        //获取当前的所有服务名称
        List<String> swaggerResources = swaggerClient.swaggerResources();
        log.info(JSONObject.toJSONString(swaggerResources));
        String url;
        DruidMonitorDO druidMonitorDO;
        for (String s : swaggerResources) {
            if (s.equals(serviceName)){
                continue;
            }
            map.put("serviceName", s);
            url = nacosService + getInstanceList;
            //根据名称获取每个服务下的实例
            String result = HttpUtil.createGet(url).form(map).execute().body();
            String hosts = JSONObject.parseObject(result).getString("hosts");
            JSONArray jsonArray = JSONObject.parseArray(hosts);
            for (Object object : jsonArray) {
                JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(object));
                druidMonitorDO = jsonObject.toJavaObject(DruidMonitorDO.class);
                druidMonitorDO.setMonitorUrl("http://" + jsonObject.getString("ip") + StrUtil.COLON +
                        jsonObject.getString("port") + StrUtil.SLASH + druidManagerUrl);
                list.add(druidMonitorDO);
            }
        }
        page.setRecords(list);
        page.setTotal(list.size());
        return page;
    }
}